<script setup lang="ts">
import { ref, onBeforeMount } from "vue";
import ReCol from "@/components/ReCol";
import { formRules } from "./utils/rule";
import { FormProps } from "./utils/types";
import { usePublicHooks } from "../hooks";
// 假接口，实际使用时需要替换为真实接口
import { getAllUserList } from "@/api/system";

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    higherDeptOptions: [],
    parentId: 0,
    name: "",
    nickname: "",
    sort: 0,
    status: 1,
    remark: ""
  })
});

const ruleFormRef = ref();
const { switchStyle } = usePublicHooks();
const newFormInline = ref(props.formInline);

// 用户列表相关变量
const userList = ref([]);
const allUsers = ref([]); // 存储所有用户数据
const userLoading = ref(false);
const isUsersLoaded = ref(false); // 标记用户数据是否已加载
const showUserSelect = ref(false); // 控制是否显示用户选择组件

// 组件挂载时加载用户数据
onBeforeMount(() => {
  loadAllUsers();
});

// 一次性加载所有用户数据
const loadAllUsers = async () => {
  if (isUsersLoaded.value) {
    showUserSelect.value = true; // 如果已经加载过，直接显示组件
    return;
  }
  userLoading.value = true;
  try {
    const res = await getAllUserList();
    if (res.success) {
      allUsers.value = res.data || [];
      userList.value = [...allUsers.value]; // 初始时显示所有用户
      isUsersLoaded.value = true; // 标记为已加载
      showUserSelect.value = true; // 数据加载完成，显示组件
    }
  } catch (error) {
    console.error("加载用户失败:", error);
    showUserSelect.value = true; // 即使加载失败，也显示组件允许用户操作
  } finally {
    userLoading.value = false;
  }
};

// 前端搜索用户
const remoteSearchUser = query => {
  if (!query) {
    userList.value = [...allUsers.value];
    return;
  }

  // 前端筛选
  userList.value = allUsers.value.filter(user =>
    user.nickname.toLowerCase().includes(query.toLowerCase())
  );
};
function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="82px"
  >
    <el-row :gutter="30">
      <re-col>
        <el-form-item label="上级部门">
          <el-cascader
            v-model="newFormInline.parentId"
            class="w-full"
            :options="newFormInline.higherDeptOptions"
            :props="{
              value: 'ID',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
            clearable
            filterable
            placeholder="请选择上级部门"
          >
            <template #default="{ node, data }">
              <span>{{ data.name }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
      </re-col>

      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="newFormInline.name"
            clearable
            placeholder="请输入部门名称"
          />
        </el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="部门负责人">
          <div v-if="showUserSelect">
            <el-select
              v-model="newFormInline.nickname"
              filterable
              clearable
              remote
              :remote-method="remoteSearchUser"
              :loading="userLoading"
              placeholder="请输入部门负责人名称搜索"
            >
              <el-option
                v-for="user in userList"
                :key="user.ID"
                :label="user.nickname"
                :value="user.ID"
              />
            </el-select>
          </div>
          <div
            v-else
            class="loading-skeleton"
            style="
              height: 32px;
              display: flex;
              align-items: center;
              justify-content: center;
              background-color: #f5f5f5;
              border-radius: 4px;
            "
          >
            <el-loading size="small" /> 加载中...
          </div>
        </el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="排序">
          <el-input-number
            v-model="newFormInline.sort"
            class="w-full!"
            :min="0"
            :max="9999"
            controls-position="right"
          />
        </el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="部门状态">
          <el-switch
            v-model="newFormInline.status"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="停用"
            :style="switchStyle"
          />
        </el-form-item>
      </re-col>

      <re-col>
        <el-form-item label="备注">
          <el-input
            v-model="newFormInline.remark"
            placeholder="请输入备注信息"
            type="textarea"
          />
        </el-form-item>
      </re-col>
    </el-row>
  </el-form>
</template>
